package com.example.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

public class ZookeeperAclDemo {
    public static void main(String[] args) throws Exception {

        String url = "192.168.232.130:2181,192.168.232.130:2182,192.168.232.130:2183";

        //使用Fluent风格api创建
        CuratorFramework framework = CuratorFrameworkFactory.builder()
                .connectString(url)
                .sessionTimeoutMs(5000)  // 会话超时时间
                .connectionTimeoutMs(5000)  // 连接超时时间
                .namespace("gupao")  // 隔离名称
                .retryPolicy(new ExponentialBackoffRetry(1000, 3)) // 重试策略
                .build();

        framework.start();

//        AclDemo(framework);
        setExistNodeAcl(framework);


    }

    public static void setExistNodeAcl(CuratorFramework framework) throws Exception {

        List<ACL> acls = new ArrayList<>();
        ACL acl_r = new ACL(ZooDefs.Perms.READ|ZooDefs.Perms.WRITE,
                new Id("digest", DigestAuthenticationProvider.generateDigest("admin:admin")));

        acls.add(acl_r);
//        framework.setACL().withACL(acls).forPath("/temp");

        // curator 内部提供了一些权限列表
        // ZooDefs.Ids.OPEN_ACL_UNSAFE 开发权限
        // ZooDefs.Ids.CREATOR_ALL_ACL 创建者拥有权限
        // ZooDefs.Ids.READ_ACL_UNSAFE 读权限
        framework.setACL().withACL(ZooDefs.Ids.READ_ACL_UNSAFE).forPath("/temp");
    }

    public static void AclDemo(CuratorFramework framework) throws Exception {

        String nodeKey = "/auth";
        framework.delete().forPath(nodeKey);

        List<ACL> acls = new ArrayList<>();
        ACL acl_r = new ACL(ZooDefs.Perms.READ|ZooDefs.Perms.WRITE,
                new Id("digest", DigestAuthenticationProvider.generateDigest("admin1:admin1")));

        acls.add(acl_r);

        framework.create().withMode(CreateMode.PERSISTENT)
                .withACL(acls)
                .forPath(nodeKey);
    }
}
